package com.brsya.movie.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.brsya.base.base.BaseLayoutFragment;
import com.brsya.base.base.Contents;
import com.brsya.base.bean.MovieBean;
import com.brsya.base.recycler.BaseAdapter;
import com.brsya.base.util.LoggerUtil;
import com.brsya.base.util.StringUtil;
import com.brsya.movie.R;
import com.brsya.movie.adapter.SearchHistoryAdapter;
import com.brsya.movie.application.MyApplication;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Brsya
 * CreateDate: 2022/7/7  15:58
 * Description:
 * 搜索历史
 */
public class SearchHistoryFragment extends BaseLayoutFragment {
    private RecyclerView rlList;
    private TextView tvNoData;
    private RelativeLayout rlAdBox;


    private SearchHistoryAdapter adapter;
    private List<MovieBean> historyList;


    private OnClickItemListener onClickItemListener;

    public static SearchHistoryFragment newInstance() {

        Bundle args = new Bundle();

        SearchHistoryFragment fragment = new SearchHistoryFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_search_history);
        rlList = findViewById(R.id.rl_list);
        rlAdBox = findViewById(R.id.rl_ad_box);
        tvNoData = findViewById(R.id.tv_no_data);
    }

    @Override
    protected void initData() {

        String jsonStr = MyApplication.aCache.getAsString(Contents.CACHE_KEY_SEARCH_HISTORY);
        if (!StringUtil.isEmpty(jsonStr)) {
            historyList = JSON.parseArray(jsonStr, MovieBean.class);
        }

        rlList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        rlList.setAdapter(adapter = new SearchHistoryAdapter(getContext()));


        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<MovieBean>() {
            @Override
            public void onItemClick(int position, MovieBean data) {
                if (onClickItemListener != null) {
                    onClickItemListener.onClickItem(data);
                }
                updateHistory(data);
            }
        });


        if (historyList == null) {
            historyList = new ArrayList<>();
            rlList.setVisibility(View.GONE);
            tvNoData.setVisibility(View.VISIBLE);
        } else {
            adapter.setDataList(historyList);
            rlList.setVisibility(View.VISIBLE);
            tvNoData.setVisibility(View.GONE);
        }

        loadAd();
    }

    /**
     * 更新历史记录
     *
     * @param data 更新的历史
     */
    public void updateHistory(MovieBean data) {
        int position = isContains(data);
        if (position >= 0) {
            historyList.remove(position);
        }
        historyList.add(0, data);
        for (int i = 20; i < historyList.size(); i++) {
            historyList.remove(i);
        }
        adapter.setDataList(historyList);
        adapter.notifyDataSetChanged();
        MyApplication.aCache.put(Contents.CACHE_KEY_SEARCH_HISTORY, JSON.toJSONString(historyList));
    }

    /**
     * 判断列表中是否存在
     *
     * @param data 判断的数据
     * @return 列表中的位置，如果列表中不存在，返回-1
     */
    public int isContains(MovieBean data) {
        for (int i = 0; i < historyList.size(); i++) {
            MovieBean movieBean = historyList.get(i);
            if (movieBean.getId() == data.getId()) {
                return i;
            }
        }
        return -1;
    }

    private void loadAd() {
        // 加载广告
        float width = getContext().getResources().getDisplayMetrics().xdpi;
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(getActivity());

        AdSlot adSlot = new AdSlot.Builder()
                // 广告ID 948498437 948498604
                .setCodeId(Contents.AD_TT_SDK_SETTING_ID)
                .setSupportDeepLink(true)
                .setAdCount(1)
                // 期望模板广告view的size,单位dp
                .setExpressViewAcceptedSize(width, 0)
                .setAdloadSeq(1)
                .build();

        adNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {

            @Override
            public void onError(int i, String s) {
                LoggerUtil.i("穿山甲广告加载失败" + i + "--ss--" + s);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                LoggerUtil.i("穿山甲广告加载成功");
                rlAdBox.removeAllViews();
                for (TTNativeExpressAd adBean : list) {
                    rlAdBox.addView(adBean.getExpressAdView());
                    adBean.render();

                    adBean.setDislikeCallback(getActivity(), new TTAdDislike.DislikeInteractionCallback() {
                        @Override
                        public void onShow() {
                            if (rlAdBox != null) {
                                rlAdBox.removeAllViews();
                                rlAdBox.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onSelected(int i, String s, boolean b) {

                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                }
            }
        });


    }


    public void setOnClickItemListener(OnClickItemListener onClickItemListener) {
        this.onClickItemListener = onClickItemListener;
    }

    /**
     * 点击搜索历史监听
     */
    public interface OnClickItemListener {
        /**
         * 点击搜索历史
         *
         * @param data 搜索数据
         */
        void onClickItem(MovieBean data);
    }
}
